import { useEffect, useState, useReducer, useContext, useRef } from 'react'
import { Tooltip, Button } from '@arco-design/web-react';
import { IconLeft } from '@arco-design/web-react/icon';
import { useParams } from "react-router-dom";

import { previewPostMessage, PageContext, pageContextReducer, pageContextStore } from '@/store/pageContext';
import { queryCardDB, updateThemeConfigDB, updateCardDB, updateGlobalDB, getGlobalDB } from "@/api/indexedDB";
import CreateComponents from '@/components/renderComponent/index';

import { getGlobalValue } from '@/tool/settingConfigFilter';


import PageMenu from './components/pageMenu';
import GlobalMenu from './components/globalMenu';
import Blocks from './components/block';
import Drawer from './components/drawer';



function AppTemplateLeftNav({ tips, children, active, onClick }) {
  return <Tooltip position='right' trigger='hover' content={tips}>
    <div onClick={onClick} className={`w-10 h-10 rounded-md flex cursor-pointer justify-center items-center text-gray-500 ${active ? 'bg-red-200 text-red-500' : 'hover:bg-slate-100'}`}>
      {children}
    </div>
  </Tooltip>
}


function SettingHeader({ onClick }) {
  return <>
    <span className='pr-2 cursor-pointer' onClick={onClick}>
      <IconLeft />
    </span>
    <span>设置</span>
  </>
}

function AppTemplateLeft({ GlobalConfig, themeId }) {
  const { state } = useContext(PageContext);

  const [current, setCurrent] = useState('page');

  const [currentBlock, setCurrentBlock] = useState({ id: "" });

  // 配置项
  const [settings, setSettings] = useState([])
  // 显示配置项
  const [settingsShow, setSettingsShow] = useState(false)
  // 获取配置项
  function hanldeMap(item, index) {
    if (current === 'page') {
      setSettings(item.settings);
      setCurrentBlock(item)
    } else {
      setSettings(item.settings);

    }
    setSettingsShow(true)
  }

  function componentsChange(item, index, value) {
    // 设置集合
    const settingIds = {}
    const updatedItems = settings.map((el, i) => {
      // 设置修改值
      if (index === i) {
        el.default = value;
      }

      // 获取当前配置集合key value
      if (el.id) {
        settingIds[el.id] = el.default
      }
      return el
    });
    setSettings(updatedItems)


    if (current === 'page') {
      const upDateState = state.find(item => item.id === currentBlock.id)
      upDateState.default.settings = settingIds;
      updateCardDB(upDateState);
      previewPostMessage({ data: upDateState, type: "update" })

    } else {
      updateGlobalDB({ id: themeId, data: GlobalConfig })
      previewPostMessage({ data: getGlobalValue(GlobalConfig), type: "global" })
    }
  }


  function handleCuurentModel(type) {
    setCurrent(type)
    setSettingsShow(false)
  }

  return <div className='h-full overflow-hidden'>

    <div className='flex  h-full'>
      <div className='h-full text-lg flex flex-col items-center p-3 gap-2 border-r-default'>
        <AppTemplateLeftNav tips="页面设置" onClick={handleCuurentModel.bind(null, 'page')} active={current === 'page'}>
          <i className='oem-icon icon-duotu5'></i>
        </AppTemplateLeftNav>
        <AppTemplateLeftNav tips="全局设置" onClick={handleCuurentModel.bind(null, 'global')} active={current === 'global'}>
          <i className='oem-icon icon-Configuration'></i>
        </AppTemplateLeftNav>
      </div>
      <div className='flex-1 w-64 relative overflow-hidden'>
        <Drawer header='页面设置' visible={current === 'page'}>
          <PageMenu onchange={hanldeMap} themeId={themeId} value={currentBlock.id} />
        </Drawer>

        <Drawer header='全局设置' visible={current === 'global'}>
          <GlobalMenu value={GlobalConfig} onchange={hanldeMap} />
        </Drawer>

        <Drawer header={<SettingHeader onClick={() => { setSettingsShow(false) }} />} visible={settingsShow}>
          <CreateComponents components={settings} onChange={componentsChange} />
        </Drawer>
      </div>
    </div>
  </div>
}



function LayoutHeader({ themeConfig, GlobalConfig,onNameChange }) {

  const { state } = useContext(PageContext);

  // updateThemeConfigDB

  function handleCreateTheme() {
    fetch("/api/create/theme", {
      method: "post",
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        global: GlobalConfig, cardList: state, themeConfig: themeConfig
      })
    }).then(response => response.json())
      .then(data => console.log(data));
  }

  return <div className='h-14 bg-white border-b-default px-3 flex justify-between items-center'>
    <div>
      <input defaultValue={themeConfig.name} onBlur={onNameChange} className='border-none font-medium' />
      {/* <span className='font-medium'>{themeConfig.name}</span> */}
    </div>
    <div className='flex gap-3'>
      <Button type='primary' onClick={handleCreateTheme}>生成模版</Button>
      {/* <Button type='primary'>同步设置</Button> */}
    </div>
  </div>
}

export default function AppTemplate() {

  const params = useParams();
  //全局数据
  const [config, setConfig] = useState([]);

  //全局数据
  const [themeConfig, setThemeConfig] = useState({ name: "" });

  const [state, dispatch] = useReducer(pageContextReducer, pageContextStore);


  function handleChangeName(e) {
    setThemeConfig((perv) => {
      perv['name'] = e.target.value;
      updateThemeConfigDB(params.id, perv)
      return perv
    })

  }

  useEffect(() => {
    window.addEventListener('message', function (res) {
      if (res.data.origin === "moi" && res.data.type === "load") {
        if (params.id) {
          getGlobalDB(params.id).then((result) => {
            if (result) {
              setConfig(result.data)
              previewPostMessage({ data: getGlobalValue(result.data), type: "global" })

            }
          })
          queryCardDB(params.id).then((result) => {
            if (result) {
              dispatch({ type: "init", data: result.data })
              setThemeConfig(result.config)
            }
          });
        } else {
          alert("模版错误")
        }
      }
    })
  }, [])
  return (
    <PageContext.Provider value={{ state, dispatch }}>
      <div className='w-screen flex flex-col h-screen  overflow-hidden'>
        {/* <LayoutHeader themeConfig={themeConfig} GlobalConfig={config} onNameChange={handleChangeName} />
        <div className='flex flex-1'>
          <AppTemplateLeft GlobalConfig={config} themeId={params.id} />
          <div className='flex-1 flex-shrink-0 bg-gray-100 p-3'>
            <Blocks />
          </div>
        </div> */}
        <iframe src="/test" className='w-full h-full' frameborder="0"></iframe>
        {/* <div className='w-64 border-l border-gray-100 border-solid h-full overflow-x-hidden overflow-y-auto px-3'>
        <CreateComponents components={settings} onChange={componentsChange} />
      </div> */}
      </div>
    </PageContext.Provider>

  )
}